package com.gridmobi.xrtb.conf;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import java.util.Properties;

/**
 * @author huangyongchao
 * 不破坏spring data的默认配置 基于配置单独构造一个kafka producer ，没有做单例 没有实现close 要手动实现close
 * 适合流数据 很久不要关闭的场景
 */
//@Configuration
public class KafkaConf {
    @Value("${spring.kafka.producer.acks}")
    private String acks = "1";
    @Value("${spring.kafka.producer.client-id}")
    private String client;
    @Value("${spring.kafka.producer.compression-type}")
    private String compression = "lz4";
    @Value("${spring.kafka.bootstrap-servers}")
    private String servers;


    @Bean
    public Properties producerConfigs() {
        Properties props = new Properties();
        props.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
        props.setProperty(ProducerConfig.RETRIES_CONFIG, "0");
        props.setProperty(ProducerConfig.CLIENT_ID_CONFIG, client);
        props.setProperty(ProducerConfig.COMPRESSION_TYPE_CONFIG, compression);
        props.setProperty(ProducerConfig.BATCH_SIZE_CONFIG, "10000");
        props.setProperty(ProducerConfig.LINGER_MS_CONFIG, "5");
        props.setProperty(ProducerConfig.BUFFER_MEMORY_CONFIG, "33554432");
        props.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.setProperty(ProducerConfig.ACKS_CONFIG, acks);
        props.setProperty(ProducerConfig.RETRIES_CONFIG, "3");
        //props.setProperty(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");

        return props;
    }

    @Bean
    @Qualifier("rtbproducer")
    public Producer<String, String> producer() {
        return new KafkaProducer<>(producerConfigs());

    }


}
